
from PyQt5.QtCore import Qt, QTimer
from PyQt5.QtGui import QImage, QPixmap
import cv2


class VideoViewer:
    def __init__(self, label_qian, label_hou):
        self.label_qian = label_qian
        self.label_hou = label_hou
        self.cascade_classifier = cv2.CascadeClassifier(
            'D:/Programming_Softwares/OpenCV/opencv/sources/data/haarcascades/haarcascade_frontalface_alt2.xml'
        )

    def load_video(self, file_path):
        self.video = cv2.VideoCapture(file_path)
        self.timer = QTimer()
        self.timer.timeout.connect(self.show_video)
        self.timer.start(30)

    def show_video(self):
        ret, frame = self.video.read()
        if ret:
            # 原始视频帧（BGR）
            original_frame = frame.copy()

            # 处理视频帧（转换为灰度图，检测人脸，绘制矩形）
            gray = cv2.cvtColor(frame, cv2.COLOR_BGR2GRAY)
            faces = self.cascade_classifier.detectMultiScale(gray, scaleFactor=1.1, minNeighbors=5, minSize=(30, 30))
            for (x, y, w, h) in faces:
                cv2.rectangle(frame, (x, y), (x + w, y + h), (0, 255, 0), 2)

                # 转换处理后的视频帧为RGB并缩放
            processed_frame = cv2.cvtColor(frame, cv2.COLOR_BGR2RGB)
            processed_frame = cv2.resize(processed_frame, (300, 300))
            processed_image = QImage(processed_frame.data, processed_frame.shape[1], processed_frame.shape[0],
                                     QImage.Format_RGB888)
            processed_pixmap = QPixmap.fromImage(processed_image)

            # 在label_hou中显示处理后的视频
            self.label_hou.setPixmap(processed_pixmap.scaled(self.label_hou.size(), Qt.KeepAspectRatio))
            self.label_hou.setScaledContents(True)

            # 转换原始视频帧为RGB并缩放（如果需要）
            original_frame = cv2.cvtColor(original_frame, cv2.COLOR_BGR2RGB)
            # 如果不需要缩放，可以跳过下面的cv2.resize
            # original_frame = cv2.resize(original_frame, (some_width, some_height))
            original_image = QImage(original_frame.data, original_frame.shape[1], original_frame.shape[0],
                                    QImage.Format_RGB888)
            original_pixmap = QPixmap.fromImage(original_image)

            # 在label_qian中显示原视频
            self.label_qian.setPixmap(original_pixmap)
            self.label_qian.setScaledContents(True)
            # 如果label_qian也需要缩放，可以像上面那样使用scaled方法
            # 注意：如果设置了setScaledContents(True)，则不需要手动调用scaled
